<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col v-if="isDealName" :span="12">
          <el-form-item :label="$t('项目名称')" prop="dealId">
            <MainBodySelect
              v-model="form.dealId"
              :scope-authority="true"
              parameters="deal"
              @change="changeDeal"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('是否上市')" prop="company">
            <el-radio-group v-model="form.company" @change="companyChange">
              <el-radio
                v-for="dict in companyOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('估值时间')" prop="valuationTime">
            <DatePicker v-model="form.valuationTime" :placeholder="$t('估值时间')" @change="changeInvestorList(); getWebRate()" />
          </el-form-item>
        </el-col>
        <el-col v-if="!companyIsShow" :span="12">
          <el-form-item :label="$t('估值方法')" prop="valuationMethod">
            <el-select v-model="form.valuationMethod" filterable :placeholder="$t('估值方法')" @change="valuationMethodChange">
              <el-option
                v-for="dict in valuationMethodOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="!valuationMethodIsShow && !companyIsShow && valuationMethodIsShowBySys" :span="12">
          <el-form-item :label="$t('可比公司法')" prop="comparableCompanyLaw">
            <el-select v-model="form.comparableCompanyLaw" filterable :placeholder="$t('可比公司法')">
              <el-option
                v-for="dict in comparableCompanyLawOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="valuationMethodIsShow && !companyIsShow && valuationMethodIsShowBySys" :span="12">
          <el-form-item :label="$t('可比交易法')">
            <el-input v-model="form.comparableCompanyLaw" :placeholder="$t('可比交易法')" />
          </el-form-item>
        </el-col>
        <el-col v-if="!valuationMethodIsShow && !companyIsShow && valuationMethodIsShowBySys" :span="12">
          <el-form-item :label="(form.comparableCompanyLaw === 'PS' ? $t('营业收入') : form.comparableCompanyLaw === 'PE' ? $t('净利润') : $t('净资产')) + $t('金额单位')" prop="netProfit">
            <money v-model="form.netProfit" unit="w" />
          </el-form-item>
        </el-col>
        <el-col v-if="!valuationMethodIsShow && !companyIsShow && valuationMethodIsShowBySys" :span="12">
          <el-form-item :label="$t('{item} 倍数', { item: form.comparableCompanyLaw })" prop="multiple">
            <el-input-number v-model="form.multiple" :placeholder="$t('{item} 倍数', { item: form.comparableCompanyLaw })" :controls="false" :precision="2" style="width:100%;" />
          </el-form-item>
        </el-col>
        <el-col v-if="companyIsShow" :span="12">
          <el-form-item :label="$t('持有股数')" prop="numberSharesHeld">
            <money v-model="form.numberSharesHeld" />
          </el-form-item>
        </el-col>
        <el-col v-if="companyIsShow" :span="12">
          <el-form-item :label="$t('基准日股价(元)')" prop="dailySharePrice">
            <money v-model="form.dailySharePrice" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.company === 'Y'" :span="12">
          <el-form-item :label="$t('项目估值') + $t('金额单位')" prop="projectValuation">
            <span slot="label">
              {{ $t('项目估值') }} {{ $t('金额单位') }}
              <el-tooltip :content="$t('持有股数 * 基准日股价')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <money v-model="form.projectValuation" unit="w" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.company === 'N'" :span="12">
          <el-form-item :label="$t('公司整体估值') + $t('金额单位')" prop="companyValuation">
            <span slot="label">
              {{ $t('公司整体估值') }} {{ $t('金额单位') }}
              <el-tooltip v-if="valuationMethodIsShowBySys" placement="top">
                <div slot="content">
                  <span v-html="$t('可比公司法 - PE： 净利润 * PE倍数<br>')" />
                  <span v-html="$t('可比公司法 - PB： 净资产 * PB倍数<br>')" />
                  <span v-html="$t('可比公司法 - PS： 营业收入* PS倍数')" />
                </div>
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <money v-model="form.companyValuation" unit="w" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('总股数(万股)/注册资本(万)')" prop="totalNumberOfShares">
            <money v-model="form.totalNumberOfShares" unit="w" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('持股比例(%)')" prop="shareholdingRatio">
            <span slot="label">
              {{ $t('持股比例(%)') }}
              <el-tooltip :content="$t('出资主体列表最新持股比例之和')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <Ratio v-model="form.shareholdingRatio" :placeholder="$t('持股比例(%)')" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.company === 'Y'" :span="12">
          <el-form-item :label="$t('公司整体估值') + $t('金额单位')" prop="companyValuation">
            <span slot="label">
              {{ $t('公司整体估值') }}{{ $t('金额单位') }}
              <el-tooltip placement="top">
                <div slot="content">
                  {{ $t('项目估值 / 持股比例') }}
                </div>
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <money v-model="form.companyValuation" unit="w" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.company === 'N'" :span="12">
          <el-form-item :label="$t('项目估值') + $t('金额单位')" prop="projectValuation">
            <span slot="label">
              {{ $t('项目估值') }}{{ $t('金额单位') }}
              <el-tooltip :content="$t('(公司整体估值 * 持股比例) / 100')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <money v-model="form.projectValuation" unit="w" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('币种')" prop="currency">
            <el-select v-model="form.currency" :placeholder="$t('币种')" @change="setRateByInvestor">
              <el-option
                v-for="dict in currencyOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('总投资成本') + $t('金额单位')" prop="totalInvestmentCost">
            <span slot="label">
              {{ $t('总投资成本') }}{{ $t('金额单位') }}
              <el-tooltip :content="$t('出资主体列表实际投资金额总和')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <money v-model="form.totalInvestmentCost" unit="w" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('剩余投资成本') + $t('金额单位')" prop="totalInvestmentRemainingCost">
            <span slot="label">
              {{ $t('剩余投资成本') }}{{ $t('金额单位') }}
              <el-tooltip :content="$t('投资成本 - 回款本金')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <money v-model="form.totalInvestmentRemainingCost" unit="w" disabled />
          </el-form-item>
        </el-col>
        <el-col
          v-for="(item, index) in form.exchangeRateWeb"
          :key="new Date().getTime() + '_' + index"
          :span="12"
        >
          <el-form-item :prop="'exchangeRateWeb.' + index + '.rate'" :rules="[{ required: true, message: $t('必填信息'), trigger: ['blur', 'change'] }]">
            <span slot="label">
              {{ $t(formatCurrency(item.sourceCurrency)) }}{{ $t('对') }}{{ $t(formatCurrency(item.targetCurrency)) }}{{ $t('汇率') }}
              <el-tooltip :content="$t('使用') + item.placeholder" placement="right">
                <el-button
                  v-if="item.placeholder !== undefined && item.placeholder !== null && item.placeholder !== ''"
                  class="el-icon-document-copy"
                  size="small"
                  type="text"
                  style="color: #1890ff !important;cursor: pointer;"
                  @click="inputPlaceholder(index, item.placeholder)"
                />
              </el-tooltip>
            </span>
            <el-input-number
              v-model="item.rate"
              :max="999999999"
              :min="0"
              :disabled="form.sourceChildId && !(item.rate === undefined || item.rate === null || item.rate === '' || item.rate === 0)"
              :placeholder="item.placeholder"
              :controls="false"
              @change="changeBlurRate($event, item)"
              @blur="changeBlurRate($event, item)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('估值背景')" prop="valuationBackground">
            <el-input v-model="form.valuationBackground" type="textarea" maxlength="2000" show-word-limit :placeholder="$t('估值背景')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('应对方案')" prop="responsePlan">
            <el-input v-model="form.responsePlan" type="textarea" maxlength="2000" show-word-limit :placeholder="$t('应对方案')" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="area-header">
        <span class="area-header-title">{{ $t('出资主体列表') }}</span>
      </div>
      <el-table :data="form.dealValuationInvestmentList" class="nowrapTable formTable" border>
        <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50">
          <template slot-scope="scope">
            {{ (1 - 1) * 999 + scope.$index + 1 }}
          </template>
        </el-table-column>
        <!--<el-table-column :label="$t('主体类型')" align="center" prop="investorType" :formatter="mainBodyTypeFormat" />-->
        <el-table-column :label="$t('主体名称')" align="center" prop="investorName" />
        <!--        <el-table-column :label="$t('币种')" align="center" prop="currency">-->
        <!--          <template slot-scope="scope">-->
        <!--            {{ $t(formatCurrency(scope.row.currency)) }}-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column :label="$t('实际投资金额') + $t('金额单位')" align="center" prop="amountInvestmentFact">
          <template slot-scope="scope">
            <span>{{ moneyFormat(scope.row.amountInvestmentFact, 'w') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('剩余投资成本') + $t('金额单位')" align="center" prop="remainingInvestmentCost">
          <template slot-scope="scope">
            <span>{{ moneyFormat(scope.row.remainingInvestmentCost, 'w') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="latestShareholdingRatio" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('最新持股比例(%)') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item
              :prop="'dealValuationInvestmentList.' + scope.$index + '.latestShareholdingRatio'"
              :rules="rules.checkMoney"
            >
              <Ratio v-model="scope.row.latestShareholdingRatio" unit="rate" @change="updateShareholdingRatio" />
            </el-form-item>
          </template>

        </el-table-column>
        <el-table-column :label="$t('主体持股数量') + $t('(万股)')" align="center" prop="numberOfShares">
          <template slot="header" slot-scope="{}">
            <span>{{ $t('主体持股数量') + $t('(万股)') }}</span>
          </template>
          <template slot-scope="scope">
            <el-form-item :prop="'dealValuationInvestmentList.' + scope.$index + '.numberOfShares'" :rules="dealValuationInvestmentRules.numberOfShares">
              <money v-model="scope.row.numberOfShares" unit="w" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :label="$t('主体所占项目估值') + $t('金额单位')" prop="fundProjectValuation" align="center">
          <template slot="header" slot-scope="{}">
            <i style="color: #ff4949;margin-right: 4px;">*</i>
            <span>{{ $t('主体所占项目估值') }}{{ $t('金额单位') }}</span>
            <span slot="label">
              <el-tooltip :content="$t('(公司整体估值 * 最新持股比例) / 100')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
          </template>
          <template slot-scope="scope">
            <el-form-item
              :prop="'dealValuationInvestmentList.' + scope.$index + '.fundProjectValuation'"
              :rules="rules.checkMoney"
            >
              <money v-model="scope.row.fundProjectValuation" unit="w" />
            </el-form-item>
          </template>

        </el-table-column>
      </el-table>
      <div class="tol" style="display: -webkit-box;">
        <div>
          <el-form-item :prop="'updateShareholding'" class="css-calculate-shareholding" style="margin-top: 2px;">
            <el-checkbox v-model="form.updateShareholding" :true-label="'Y'" :false-label="'N'">{{ $t('更新主体持股信息') }}</el-checkbox>
          </el-form-item>
        </div>
      </div>
      <FileTable :list.sync="form.fileList" has-permi="deal:companyvaluation" data-type="deal_company_valuation" :business-id="autoBusinessId(dealId, form)" :btn-show="!btnHide" />
    </el-form>
    <div v-if="!btnHide" slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <SaveBtn v-if="btnShow" has-permi="deal:companyvaluation" :cancel-func="cancel">
        <template v-slot:before>
          <div class="tooltip-msg">
            <span v-if="isCopy === 'copy'">{{ $t('当前数据保存后将会生成一条新的估值数据') }}</span>
          </div>
        </template>
      </SaveBtn>
    </div>
  </div>
</template>

<script>
import {
  getDealCompanyValuation,
  getStockPriceByDealId,
  saveDealCompanyValuation
} from '@/api/deal/companyvaluation/dealCompanyValuation'
import { findByDealIdToValuation, getWebRate, listDealInvestment } from '@/api/deal/investment/dealInvestment'
  import { getDealBase } from '@/api/base/deal/dealBase'
  import MainBodySelect from '@/components/MainBodySelect'
  export default {
    components: {
      MainBodySelect
    },
    props: {
      btnShow: {
        type: Boolean,
        default: true,
        desc: '是否展示按钮'
      }
    },
      data() {
        return {
          // 币种 字典currency字典
          // 是否上市 字典sys_yes_no字典
          companyOptions: [],
          // 估值方法字典
          currencyOptions: [],
          // 可比公司法字典
          valuationMethodOptions: [],
          // 表单参数
          comparableCompanyLawOptions: [],
          // 主体类型字典
          mainBodyTypeOptions: [],
          form: {
            projectValuation: 0,
            shareholdingRatio: 0,
            numberSharesHeld: 0,
            dailySharePrice: 0,
            companyValuation: 0,
            totalInvestmentCost: 0,
            totalInvestmentRemainingCost: 0,
            // 投资主体
            dealValuationInvestmentList: [],
            fileList: [],
            dealId: undefined
          },
          // 项目ID
          dealId: this.$route.query.id,
          // 根据是否上市展示不同的组件 默认否
          companyIsShow: false,
          // 根据估值方法展示不同组件 默认可比公司
          valuationMethodIsShow: false,
          // 根据估值方法展示不同组件2
          valuationMethodIsShowBySys: false,
          // 遮罩层
          loading: false,
          // 是否开启watch
          isWatch: false,
          // 是否隐藏保存等按钮
          btnHide: false,
          // 统计出资主体列表最新持股比例和
          shareCount: undefined,
          dealBaseData: undefined,
          isCopy: false,
          // 变更时间时, 记录下主体中用户填写的数据. 切换时间后给带出的新主题赋值上
          historicalSubjectData: [],
          // 当前项目主体列表
          dealInvestmentList: [],
          // 表单校验
          rules: {
            company: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            valuationTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            companyValuation: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
            shareholdingRatio: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            projectValuation: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
            currency: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
            valuationBackground: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
            netProfit: [
              { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
            ],
            multiple: [
              { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
            ],
            valuationMethod: [
              { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
            ],
            comparableCompanyLaw: [
              { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
            ],
            numberSharesHeld: [
              { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
            ],
            dailySharePrice: [
              { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
            ],
            checkMoney: [
              { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
            ],
            dealId: [
              { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
            ]
          },
          dealValuationInvestmentRules: {
            // numberOfShares: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }]
          },
          // 是否展示项目名称
          isDealName: this.$attrs.parameter && this.$attrs.parameter.quick && this.$attrs.parameter.quick === 'true'
        }
      },
      // 监听属性变化计算值
      watch: {
        // 监听持有股数
        'form.numberSharesHeld': {
          handler(val) {
            if (this.isWatch) {
              // 项目估值 = 持有股数 * 基准日股价
              this.$set(this.form, 'projectValuation', val * this.form.dailySharePrice)
            }
          }
        },
        // 监听基准日股价
        'form.dailySharePrice': {
          handler(val) {
            if (this.isWatch) {
              // 项目估值 = 持有股数 * 基准日股价 / 10000
              // this.form.projectValuation = val * this.form.numberSharesHeld / 10000
              this.$set(this.form, 'projectValuation', val * this.form.numberSharesHeld)
            }
          }
        },
        // 监听项目估值
        'form.projectValuation': {
          handler(val) {
            if (this.isWatch) {
              if (this.form.company === 'Y') {
                this.$set(this.form, 'companyValuation', val / (this.form.shareholdingRatio / 100))
              }
            }
          }
        },
        // 监听持股比例
        'form.shareholdingRatio': {
          handler(val) {
            if (this.isWatch) {
              if (this.form.company === 'N') {
                // 项目估值 = 公司整体估值 * 持股比例 / 100
                if (val != null && val !== 0) {
                  // this.form.companyValuation = this.form.projectValuation / val
                  if (!isNaN(this.form.companyValuation * val / 100)) {
                    this.$set(this.form, 'projectValuation', this.form.companyValuation * val / 100)
                  }
                }
              } else {
                this.$set(this.form, 'companyValuation', this.form.projectValuation / (val / 100))
              }
            }
          }
        },
        // 监听公司整体估值
        'form.companyValuation': {
          handler(val) {
            if (this.isWatch) {
              if (this.form.company === 'N') {
                this.$set(this.form, 'projectValuation', val * this.form.shareholdingRatio / 100)
              }
              // 出资主体列表 -> 主体所占项目估值 = (公司整体估值 * 最新持股比例) / 100
              this.form.dealValuationInvestmentList.forEach((e, i) => {
                if (!isNaN((val * e.latestShareholdingRatio) / 100) && e.latestShareholdingRatio) {
                  this.$set(e, 'fundProjectValuation', (val * e.latestShareholdingRatio) / 100)
                }
                this.$set(this.form.dealValuationInvestmentList, i, e)
                this.$forceUpdate()
              })
            }
          }
        },
        // 监听净利润/净资产/营业收入
        'form.netProfit': {
          handler(val) {
            if (this.isWatch) {
              // 可比公司法 - PE： 净利润 * PE倍数
              // 可比公司法 - PB： 净资产 * PB倍数
              // 可比公司法 - PS： 营业收入 * PS倍数
              if (this.form.company === 'N') {
                this.$set(this.form, 'companyValuation', val * this.form.multiple)
              }
            }
          }
        },
        // 监听 PE/PB/PS倍数
        'form.multiple': {
          handler(val) {
            if (this.isWatch) {
              this.$set(this.form, 'companyValuation', this.form.netProfit * val)
            }
          }
        }
      },
      created() {
        this.getDicts('sys_yes_no').then(response => {
          this.companyOptions = response.data
        })
        this.getDicts('currency').then(response => {
          this.currencyOptions = response.data
        })
        this.getDicts('valuation_method').then(response => {
          this.valuationMethodOptions = response.data
        })
        this.getDicts('comparable_company').then(response => {
          this.comparableCompanyLawOptions = response.data
        })
        this.getDicts('deal_investment_type').then(response => {
          this.mainBodyTypeOptions = response.data
        })
        this.$bus.$emit('async_done')
      },
    mounted() {
      if (this.isNotEmpty(this.dealId) && this.$parent.$parent.fundValuationQuickAddData !== undefined) {
        this.$nextTick(() => {
          listDealInvestment({ dealId: this.dealId }).then(response => {
            this.dealInvestmentList = response.rows
          })
        })
      }
    },
    methods: {
        // 初始化数据
        init(data, isCopy) {
          this.loading = true
          this.isCopy = isCopy
          this.historicalSubjectData = []
          this.dealId = this.dealId ? this.dealId : (data && data.dealId ? data.dealId : null)
          if (data && data.id !== undefined) {
            getDealCompanyValuation(data.id).then(response => {
              this.form = response.data
              this.form.exchangeRateWeb = JSON.parse((this.form.exchangeRate === undefined || this.form.exchangeRate === null || this.form.exchangeRate === '') ? '[]' : this.form.exchangeRate)
              // 复制数据清空ID
              if (isCopy === 'copy') {
                this.form.id = undefined
                this.form.sourceChildId = undefined
                this.form.dealValuationInvestmentList && this.form.dealValuationInvestmentList.forEach(item => {
                  item.id = undefined
                })
                this.form.fileList && this.form.fileList.forEach(item => {
                  item.fileSource = item.id
                  item.id = undefined
                })
              }
              var _this = this
              // 获取当前项目信息币种及其信息
              getDealBase(_this.dealId).then(response => {
                _this.dealBaseData = response.data
                if (_this.form.currency === null || _this.form.currency === undefined || _this.form.currency === '') {
                  _this.form.currency = _this.dealBaseData.currency
                }
                if (_this.form.exchangeRateWeb === undefined || _this.form.exchangeRateWeb === null || _this.form.exchangeRateWeb.length <= 0) {
                  _this.$nextTick(() => {
                    _this.setRateByInvestor()
                  })
                }
              })
              this.$nextTick(() => {
                this.form.shareholdingRatio = response.data.shareholdingRatio
              })
              this.initShowField()
              this.$forceUpdate()
              // this.companyChange(this.form.company)
              // this.valuationMethodChange(this.form.valuationMethod)
              setTimeout(() => {
                this.isWatch = true
              }, 100)
              this.loading = false
            })
          } else {
            this.isWatch = true
            this.reset()
            if (this.dealId) {
              this.getDealData()
            } else {
              this.loading = false
            }
          }
        },
      // 获取当前项目信息币种及其信息
      getDealData() {
        var _this = this
        getDealBase(_this.dealId).then(response => {
          _this.dealBaseData = response.data
          if (_this.form.currency === null || _this.form.currency === undefined || _this.form.currency === '') {
            _this.form.currency = _this.dealBaseData.currency
            if (response.data.dealBaseEquity) {
              _this.form.totalNumberOfShares = response.data.dealBaseEquity.totalShare
            }
          }
          _this.companyChange(_this.form.company)
          // 判断字段展示
          _this.initShowField()
          // 初始话当前时间前的投资主体数据
          _this.changeInvestorList()
        })
      },
      // 项目名称点击事件
      changeDeal(dealId) {
          alert(3)
        this.dealId = dealId
        this.getDealData()
      },
        getWebRate() {
          this.form.exchangeRateWeb.forEach((item, index) => {
            if (item !== undefined && item.targetCurrency !== undefined && item.sourceCurrency !== undefined) {
              getWebRate(item.targetCurrency, item.sourceCurrency, this.form.valuationTime).then(response => {
                if (response.data !== '' && response.data !== null) {
                  item.placeholder = response.data
                  this.$set(this.form.exchangeRateWeb[index], 'placeholder', this.$t('近期汇率参考') + ': ' + response.data)
                  this.$forceUpdate()
                }
              })
            }
          })
        },
        inputPlaceholder(index, val) {
          if (val !== undefined && val !== null && val !== '') {
            val = val.replaceAll('近期汇率参考', '').replaceAll(':', '').trim()
            this.$set(this.form.exchangeRateWeb[index], 'rate', parseFloat(val))
            this.$forceUpdate()
          }
        },
        // 根据估值时间获取对应的时间段前的投资数据
        changeInvestorList() {
          if (!this.dealId) {
            this.$message({
              message: '请先选择项目名称!',
              type: 'warning'
            })
            return
          }
          console.log('changeInvestorList')
          // 根据估值时间获取基准日股价
          if (this.form.valuationTime && this.form.company === 'Y') {
            getStockPriceByDealId(this.dealId, this.parseTime(this.form.valuationTime)).then(response => {
              this.form.dailySharePrice = response.data
            })
          }
          this.loading = true
          // 变更时间时, 记录下主体中用户填写的数据. 切换时间后给带出的新主题赋值上
          if (this.form.dealValuationInvestmentList) {
            this.historicalSubjectData = JSON.parse(JSON.stringify(this.form.dealValuationInvestmentList))
          }
          this.form.dealValuationInvestmentList = []
          this.form.totalInvestmentCost = 0
          this.form.shareholdingRatio = 0
          this.form.totalInvestmentRemainingCost = 0
          findByDealIdToValuation(this.dealId, this.parseTime(this.form.valuationTime)).then(response => {
            this.form.dealValuationInvestmentList = response.data
            // 当前项目全部投资主体相加算出总投资成本
            this.form.dealValuationInvestmentList.forEach((e) => {
              e.id = null
              this.form.totalInvestmentRemainingCost += (e.remainingInvestmentCost ? e.remainingInvestmentCost : 0)
              this.form.totalInvestmentCost = this.form.totalInvestmentCost + ((e.amountInvestmentFact === undefined || e.amountInvestmentFact === null || e.amountInvestmentFact === '') ? 0 : e.amountInvestmentFact)
              this.form.shareholdingRatio += e.latestShareholdingRatio
            })
            // 根据出资主体列表 动态添加汇率
            this.$nextTick(() => {
              this.setRateByInvestor()
              // 还原用户填写的数据
              if (this.historicalSubjectData) {
                this.historicalSubjectData.forEach(top => {
                  this.form.dealValuationInvestmentList && this.form.dealValuationInvestmentList.forEach((item, index) => {
                    if (top.investorId === item.investorId) {
                      this.$set(this.form.dealValuationInvestmentList[index], 'fundProjectValuation', top.fundProjectValuation)
                    }
                  })
                })
              }
              this.historicalSubjectData = []
            })
            this.loading = false
            // 如果当前时间没有数据. 则弹出对话框提示用户
            if (this.form.dealValuationInvestmentList.length <= 0 && this.form.valuationTime !== null && this.form.valuationTime !== '' && this.form.valuationTime !== undefined) {
              this.$confirm(this.$t('该估值时间未查询到已划款的投资主体，请检查相关信息。'), this.$t('提示'), {
                confirmButtonText: this.$t('确定'),
                cancelButtonText: this.$t('取消'),
                type: 'warning'
              }).then(() => {
                // 关闭当前窗口
                this.closeForm()
              }).catch(() => {
              })
            }
          })
        },
        // 根据出资主体列表 动态添加汇率
        setRateByInvestor() {
          var currencyList = []
          this.form.exchangeRateWeb = []
          this.form.dealValuationInvestmentList && this.form.dealValuationInvestmentList.forEach(item => {
            if (item.currency !== null && item.currency !== '' && item.currency !== this.form.currency && !currencyList.includes(item.currency)) {
              currencyList.push(item.currency)
            }
          })
          currencyList.forEach(item => {
            this.form.exchangeRateWeb.push({ sourceCurrency: item, targetCurrency: this.form.currency, rate: undefined })
          })
          // 确保汇率中有当前项目币种 - 如果项目比重不为空, 并且表单币种不为空,  并且两个币种不相等. 那么就添加上该表单币种对当前项目币种之间的汇率
          if (this.dealBaseData !== null && this.isNotEmpty(this.dealBaseData) && this.isNotEmpty(this.form.currency) && this.form.currency !== this.dealBaseData.currency) {
            if (!currencyList.includes(this.dealBaseData.currency)) {
              this.form.exchangeRateWeb.push({
                sourceCurrency: this.dealBaseData.currency,
                targetCurrency: this.form.currency,
                rate: undefined
              })
            }
          }
          // 获取汇率
          this.getWebRate()
          this.$forceUpdate()
        },
        // 初始化显示字段
        initShowField() {
          this.valuationMethodIsShowBySys = true
          if (this.form.company === 'Y') {
            this.companyIsShow = true
            this.valuationMethodIsShow = false
          }
          if (this.form.valuationMethod === 'JY') {
            this.valuationMethodIsShow = true
          }
          if (this.form.valuationMethod === 'XT') {
            this.valuationMethodIsShowBySys = false
            this.companyIsShow = false
            this.valuationMethodIsShow = false
          }
          if (this.form.valuationMethod === 'GS') {
            this.valuationMethodIsShowBySys = true
            this.companyIsShow = false
            this.valuationMethodIsShow = false
          }
          if (this.form.company !== 'Y' && this.form.valuationMethod !== 'JY' && this.form.valuationMethod !== 'XT' && this.form.valuationMethod !== 'GS') {
            this.valuationMethodIsShowBySys = false
            this.companyIsShow = false
            this.valuationMethodIsShow = false
          }
        },
        // 表单重置
        reset() {
          this.form = {
            id: undefined,
            dealId: this.dealId,
            company: 'N',
            valuationTime: undefined,
            numberSharesHeld: 0,
            dailySharePrice: 0,
            companyValuation: 0,
            totalNumberOfShares: 0,
            shareholdingRatio: 0,
            projectValuation: 0,
            currency: '',
            totalInvestmentCost: 0,
            totalInvestmentRemainingCost: 0,
            valuationBackground: undefined,
            responsePlan: undefined,
            createBy: undefined,
            createTime: undefined,
            updateBy: undefined,
            updateTime: undefined,
            delFlag: undefined,
            valuationMethod: 'GS',
            comparableCompanyLaw: 'PE',
            updateShareholding: 'Y',
            multiple: 0,
            netProfit: 0,
            dealValuationInvestmentList: [] // 投资主体
          }
          this.resetForm('form')
        },
        // 取消按钮
        cancel() {
          if (this.$parent.$parent.generalValuationDealOpen !== undefined) {
            this.$parent.$parent.generalValuationDealOpen = false
          }
          if (this.$parent.$parent.$parent.valuationOpen) {
            this.$parent.$parent.$parent.valuationOpen = false
            this.$parent.$parent.$parent.valuationHandler('month')
          }
          if (this.$parent.$parent.formOpen) {
            this.$parent.$parent.formOpen = false
          }
        },
        // 关闭form页面
        closeForm() {
          // 关闭form页面遮罩层
          this.loading = false
          // 关闭form页面
          if (this.$parent.$parent.generalValuationDealOpen !== undefined) {
            this.$parent.$parent.generalValuationDealOpen = false
          }
          if (this.$parent.$parent.formOpen) {
            this.$parent.$parent.formOpen = false
          }
          // 刷新list页面
          if (this.$parent.$parent.getList !== undefined) {
            this.$parent.$parent.getList()
          }
          if (this.$parent.$parent.companyValuationChart !== undefined) {
            this.$parent.$parent.companyValuationChart()
          }
          if (this.$parent.$parent.$parent.valuationOpen) {
            this.$parent.$parent.$parent.valuationOpen = false
            this.$parent.$parent.$parent.valuationHandler('month')
          }
        },
        /** 提交按钮 */
        submitForm: function() {
          this.$refs['form'].validate(valid => {
            var flag = true
            if (this.isEmpty(this.form.dealValuationInvestmentList)) {
              flag = false
              this.msgError(this.$t('出资主体列表不能为空,请调整估值时间!'))
            }
            if (valid && flag) {
              this.loading = true
              if (this.form.company === 'Y') {
                this.form.valuationMethod = undefined
                this.form.comparableCompanyLaw = undefined
                this.form.netProfit = 0
              }
              this.$set(this.form, 'dealId', this.dealId)
              this.form.exchangeRate = JSON.stringify(this.form.exchangeRateWeb)
              saveDealCompanyValuation(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess(this.$t('保存成功'))
                  // 从基金估值处快速添加
                  this.fundValuationQuickAdd()
                  this.closeForm()
                } else {
                  this.msgError(response.msg)
                  this.loading = false
                }
              }).catch(() => {
                this.loading = false
              })
            } else {
              this.locationError(document)
            }
          })
        },
        /** 基金估值页面快速添加 **/
        fundValuationQuickAdd() {
          if (this.$parent.$parent.fundValuationQuickAddData !== undefined) {
            console.clear()
            console.table(this.dealInvestmentList)
            // 该方法调用时, 该页面为基金估值页面, 且为快速添加
            var fundId = this.$route.query.id
            var ratio = 0
            var valuationMoney = 0
            var investId = ''
            this.dealInvestmentList.forEach(item => {
              if (item.investorId === fundId) {
                investId = item.id
              }
            })
            this.form.dealValuationInvestmentList && this.form.dealValuationInvestmentList.forEach(item => {
              if (item.investorId === investId) {
                ratio = item.latestShareholdingRatio
                valuationMoney = item.fundProjectValuation
              }
            })
            const data = {
              dealId: this.form.dealId,
              latestValuationTime: this.form.valuationTime,
              dealLatestValuation: this.form.projectValuation,
              shareholdingRatio: ratio,
              fundValuation: valuationMoney,
              type: 'bf'
            }
            this.$emit('fundValuationQuickAddData', data)
          }
        },
        // 是否上市
        companyChange(value) {
          if (value === 'N') {
            this.companyIsShow = false
            this.form.numberSharesHeld = 0
            this.form.dailySharePrice = 0
            // this.form.projectValuation = undefined
            // this.form.companyValuation = undefined
            this.valuationMethodChange('GS')
          } else {
            // this.form.projectValuation = undefined
            // this.form.companyValuation = undefined
            this.companyIsShow = true
            this.form.multiple = 0
            this.valuationMethodIsShow = false
          }
        },
        // 估值方法
        valuationMethodChange(value) {
          this.form.netProfit = 0
          this.form.multiple = 0
          this.valuationMethodIsShowBySys = true
          if (value === 'GS') {
            this.valuationMethodIsShow = false
            this.form.valuationMethod = value
            this.form.comparableCompanyLaw = 'PE'
          } else if (value === 'JY') {
            this.valuationMethodIsShow = true
            this.form.comparableCompanyLaw = ''
          } else {
            this.valuationMethodIsShowBySys = false
            this.companyIsShow = false
            this.valuationMethodIsShow = false
          }
        },
        formatCurrency(val) {
          const currency = this.currencyOptions.find(obj => obj.dictValue === val)
          if (currency) {
            return currency.dictLabel
          }
          return val
        },
        changeBlurRate(val, item) {
          if (val === undefined || val === '' || val === null) {
            val = 0
          }
          if (!isNaN(val)) {
            const index = this.form.exchangeRateWeb.findIndex(obj => (obj.sourceCurrency === item.sourceCurrency && obj.targetCurrency === item.targetCurrency))
            this.$nextTick(() => {
              this.form.exchangeRateWeb[index].rate = (val === 0 ? undefined : val)
              this.$forceUpdate()
            })
          }
        },
        // 计算主表的持股比例   来源= 出资主体列表 -> 最新持股比例之和
        updateShareholdingRatio() {
          this.form.shareholdingRatio = 0
          this.form.dealValuationInvestmentList && this.form.dealValuationInvestmentList.forEach(item => {
            this.form.shareholdingRatio += this.formatNum(item.latestShareholdingRatio)
          })
          // 出资主体列表 -> 主体所占项目估值 = (公司整体估值 * 最新持股比例) / 100
          this.form.dealValuationInvestmentList.forEach((e, i) => {
            if (!isNaN((this.form.companyValuation * e.latestShareholdingRatio) / 100) && e.latestShareholdingRatio) {
              this.$set(e, 'fundProjectValuation', (this.form.companyValuation * e.latestShareholdingRatio) / 100)
            }
            this.$set(this.form.dealValuationInvestmentList, i, e)
            this.$forceUpdate()
          })
        },
        formatNum(num) {
          if (num === undefined || num === null || num === '' || isNaN(num)) {
            return 0
          }
          return parseFloat(num) === Infinity ? 0 : parseFloat(num)
        },
        isNotEmpty(val) {
          return !(val === undefined || val === null || val === '')
        },
        // 主体类型字典翻译
        // eslint-disable-next-line no-unused-vars
        mainBodyTypeFormat(row, column) {
          return this.selectDictLabel(this.mainBodyTypeOptions, row.investorType)
        }
      }

    }
</script>
<style scoped lang="scss">
.tooltip-msg {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 3.5vh;
  margin-right: 2vh;
}
/deep/.css-calculate-shareholding .el-form-item__content {
  margin-left: 20px !important;
}
</style>
